package com.beta.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.beta.em.client.ClientType;
import com.beta.service.IClientsService;
import com.gexin.rp.sdk.base.IPushResult;
import com.gexin.rp.sdk.base.impl.SingleMessage;
import com.gexin.rp.sdk.base.impl.Target;
import com.gexin.rp.sdk.base.payload.APNPayload;
import com.gexin.rp.sdk.exceptions.RequestException;
import com.gexin.rp.sdk.http.IGtPush;
import com.gexin.rp.sdk.template.NotificationTemplate;
import com.gexin.rp.sdk.template.TransmissionTemplate;
import com.beta.entity.Clients;
import com.beta.service.IPushToAppService;
import com.beta.service.ServiceException;
import lombok.Getter;
import lombok.Setter;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;
import java.util.Objects;

/**
 * Created by lichao on 2016/12/7.
 */
@Getter
@Setter
public class PushToAppService implements IPushToAppService {

    private final Logger logger = LoggerFactory.getLogger(getClass());

    //    @Value("${tui.app.id}")
    private String appId;
    //    @Value("${tui.app.key}")
    private String appKey;
    //    @Value("${tui.master.secret}")
    private String masterSecret;

    private IGtPush gtPush;

    IClientsService clientsService;

    @Override
    public void pushToSingle(Integer userId, String message, String payloadMsg) {
        if (Objects.isNull(userId)) {
            throw new ServiceException("E00113");
        }
        List<Clients> clients = clientsService.selectList(new EntityWrapper<>(new Clients().setUserId(userId)));
        for (Clients client : clients) {
            if (StringUtils.isBlank(client.getCid())) {
                continue;
            }
            if (ClientType.IOS.value.equals(client.getDevice())) {
                pushToIos(client.getCid(), message, payloadMsg);
            }
            if (ClientType.ANDROID.value.equals(client.getDevice())) {
                pushToAndroid(client.getCid(), message);
            }
        }
    }

    public void pushToIos(String cid, String message, String payloadMsg) {
//        IGtPush push = new IGtPush(appKey, masterSecret, true);
        TransmissionTemplate template = new TransmissionTemplate();
        template.setAppId(appId);
        template.setAppkey(appKey);
        APNPayload payload = new APNPayload();
        payload.setContentAvailable(1);
        payload.addCustomMsg("payload", payloadMsg);
        //简单模式APNPayload.SimpleMsg
        payload.setAlertMsg(new APNPayload.SimpleAlertMsg(message));
        template.setTransmissionType(1);
        template.setAPNInfo(payload);
        SingleMessage singleMessage = new SingleMessage();
        singleMessage.setOffline(true);
        singleMessage.setPushNetWorkType(0);
        singleMessage.setData(template);
        Target target = new Target();
        target.setAppId(appId);
        target.setClientId(cid);
        IPushResult ret = null;
        try {
            ret = gtPush.pushMessageToSingle(singleMessage, target);
        } catch (RequestException e) {
            e.printStackTrace();
            ret = gtPush.pushMessageToSingle(singleMessage, target, e.getRequestId());
        }
        if (ret != null) {
            System.out.println(ret.getResponse().toString());
        } else {
            System.out.println("服务器响应异常");
        }
    }


    public void pushToAndroid(String cid, String message) {
//        IGtPush push = new IGtPush(appKey, masterSecret, true);
        NotificationTemplate template = new NotificationTemplate();
        template.setAppId(appId);
        template.setAppkey(appKey);
        // 设置通知栏标题与内容
        template.setTitle("Shoping");
        template.setText(message);
        template.setTransmissionType(1);
//        template.setTransmissionContent("请输入您要透传的内容");
        // 配置通知栏图标
        template.setLogo("icon.png");
        // 配置通知栏网络图标
        template.setLogoUrl("");
        template.setIsRing(true);
        template.setIsVibrate(true);
        template.setIsClearable(true);

        SingleMessage singleMessage = new SingleMessage();
        singleMessage.setOffline(true);
        singleMessage.setOfflineExpireTime(24 * 3600 * 1000);
        singleMessage.setData(template);
        singleMessage.setPushNetWorkType(0);
        Target target = new Target();
        target.setAppId(appId);
        target.setClientId(cid);
        IPushResult ret = null;
        try {
            ret = gtPush.pushMessageToSingle(singleMessage, target);
        } catch (RequestException e) {
            e.printStackTrace();
            ret = gtPush.pushMessageToSingle(singleMessage, target, e.getRequestId());
        }
        String error = "服务器响应异常";
        if (ret != null) {
            error = ret.getResponse().toString();
        }
        logger.error("App推送异常: cid={}, error={}", cid, error);
    }

}
